from rest_framework import serializers

from goods.models import SKU


class CartSerializer(serializers.Serializer):
    """购物车序列化器"""
    sku_id = serializers.IntegerField(label='商品id')
    count = serializers.IntegerField(label='商品数量')
    selected = serializers.BooleanField(label='是否勾选', default=True)

    def validate(self, attrs):
        sku_id = attrs['sku_id']
        count = attrs['count']
        try:
            sku = SKU.objects.get(id=sku_id)
        except Exception as e:
            raise serializers.ValidationError('商品不存在')

        # 校验库存
        if count > sku.stock:
            raise serializers.ValidationError('库存不足')

        return attrs


class CartShowSerializer(serializers.ModelSerializer):
    """购物车显示序列化器"""
    count = serializers.IntegerField(label='商品数量')
    selected = serializers.BooleanField(label='勾选状态')

    class Meta:
        model = SKU
        fields = ('id', 'name', 'price', 'default_image_url', 'count', 'selected')


class CartDeleteSerializer(serializers.Serializer):
    """购物车记录删除序列化器"""
    sku_id = serializers.IntegerField(label='商品id')
